package com.fsm.common.xfilestroage.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fsm.common.xfilestroage.entity.FileDetail;
import com.fsm.common.xfilestroage.entity.table.FileDetailTable;
import com.fsm.common.xfilestroage.mapper.FileDetailMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.hash.HashInfo;
import org.dromara.x.file.storage.core.recorder.FileRecorder;
import org.dromara.x.file.storage.core.upload.FilePartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import java.util.Map;

@Primary
@Service
public class FileDetailService extends ServiceImpl<FileDetailMapper, FileDetail> implements FileRecorder {

    @Autowired
    private FilePartDetailService filePartDetailService;

    @Override
    public boolean save(FileInfo fileInfo) {
        try {
            FileDetail detail = toFileDetail(fileInfo);
            boolean b = save(detail);
            if (b) {
                fileInfo.setId(detail.getId());
            }
            return b;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public void update(FileInfo fileInfo) {
        try {
            FileDetail detail = toFileDetail(fileInfo);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.where(FileDetailTable.FILE_DETAIL.URL.eq(detail.getUrl()));
            queryWrapper.where(FileDetailTable.FILE_DETAIL.ID.eq(detail.getId()));
            this.getMapper().updateByQuery(detail,queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public FileInfo getByUrl(String s) {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.where(FileDetailTable.FILE_DETAIL.URL.eq(s));
            FileDetail fileDetail = this.getMapper().selectOneByQuery(queryWrapper);
            return toFileInfo(fileDetail);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean delete(String s) {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.where(FileDetailTable.FILE_DETAIL.URL.eq(s));
            this.getMapper().deleteByQuery(queryWrapper);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void saveFilePart(FilePartInfo filePartInfo) {
        filePartDetailService.saveFilePart(filePartInfo);
    }

    @Override
    public void deleteFilePartByUploadId(String s) {
        filePartDetailService.deleteFilePartByUploadId(s);
    }

    /**
     * 将 FileInfo 转为 FileDetail
     */
    public FileDetail toFileDetail(FileInfo info) throws Exception {
        FileDetail detail = BeanUtil.copyProperties(
            info, FileDetail.class, "metadata", "userMetadata", "thMetadata", "thUserMetadata", "attr", "hashInfo");
        // 这里手动获 元数据 并转成 json 字符串，方便存储在数据库中
        detail.setMetadata(valueToJson(info.getMetadata()));
        detail.setUserMetadata(valueToJson(info.getUserMetadata()));
        detail.setThMetadata(valueToJson(info.getThMetadata()));
        detail.setThUserMetadata(valueToJson(info.getThUserMetadata()));
        // 这里手动获 取附加属性字典 并转成 json 字符串，方便存储在数据库中
        detail.setAttr(valueToJson(info.getAttr()));
        // 这里手动获 哈希信息 并转成 json 字符串，方便存储在数据库中
        detail.setHashInfo(valueToJson(info.getHashInfo()));
        return detail;
    }

    /**
     * 将 FileDetail 转为 FileInfo
     */
    public FileInfo toFileInfo(FileDetail detail) throws JsonProcessingException {
        FileInfo info = BeanUtil.copyProperties(
            detail, FileInfo.class, "metadata", "userMetadata", "thMetadata", "thUserMetadata", "attr", "hashInfo");

        // 这里手动获取数据库中的 json 字符串 并转成 元数据，方便使用
        info.setMetadata(jsonToMetadata(detail.getMetadata()));
        info.setUserMetadata(jsonToMetadata(detail.getUserMetadata()));
        info.setThMetadata(jsonToMetadata(detail.getThMetadata()));
        info.setThUserMetadata(jsonToMetadata(detail.getThUserMetadata()));
        // 这里手动获取数据库中的 json 字符串 并转成 附加属性字典，方便使用
        info.setAttr(jsonToDict(detail.getAttr()));
        // 这里手动获取数据库中的 json 字符串 并转成 哈希信息，方便使用
        info.setHashInfo(jsonToHashInfo(detail.getHashInfo()));
        return info;
    }

    /**
     * 将指定值转换成 json 字符串
     */
    public String valueToJson(Object value) throws JsonProcessingException {
        if (value == null) return null;
        return JSONObject.toJSONString(value);
    }

    /**
     * 将 json 字符串转换成元数据对象
     */
    public Map<String, String> jsonToMetadata(String json) throws JsonProcessingException {
        if (StrUtil.isBlank(json)) return null;
        Map<String, String> mapObj = JSONObject.parseObject(json,Map.class);
        return mapObj;
    }

    /**
     * 将 json 字符串转换成字典对象
     */
    public Dict jsonToDict(String json) throws JsonProcessingException {
        if (StrUtil.isBlank(json)) return null;
        Dict mapObj = JSONObject.parseObject(json,Dict.class);
        return mapObj;
    }

    /**
     * 将 json 字符串转换成哈希信息对象
     */
    public HashInfo jsonToHashInfo(String json) throws JsonProcessingException {
        if (StrUtil.isBlank(json)) return null;
        return JSONObject.parseObject(json,HashInfo.class);
    }
}
